<template>
  <div class="app-container">
    <!-- 查询start -->
    <div class="filter-container">
      <el-input v-model="queryParams.email" placeholder="电子邮箱" style="width: 200px;" class="filter-item" />
      <el-input v-model="queryParams.userId" placeholder="User ID" style="width: 200px;" class="filter-item" />
      <el-select v-model="queryParams.channelType" placeholder="注册渠道" clearable style="width: 200px" class="filter-item">
        <el-option
          v-for="item in channelTypes"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="queryParams.vipVersion" placeholder="会员版本" clearable style="width: 200px" class="filter-item">
        <el-option
          v-for="item in productList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <!--<el-select v-model="queryParams.expired" placeholder="过期时间" clearable style="width: 200px" class="filter-item">
        <el-option
          v-for="item in expireds"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>-->
      <el-select v-model="queryParams.state" placeholder="帐号状态" clearable style="width: 200px" class="filter-item">
        <el-option
          v-for="item in userState"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
    </div>
    <!-- 查询end -->
    <table-model ref="tableModel" :page-fun="getPage" :is-load="false" :handler-data="handelData" :control-column="true" style="margin-top: 10px" :columns="columns">
      <template slot="Button" slot-scope="scope">
        <el-button type="primary" size="small" @click="getUserInfo(scope.row)">编辑</el-button>
        <el-button v-if="scope.row.enable === 1" type="warning" size="small" @click="userEnable(scope.row.userId,false)">禁用</el-button>
        <el-button v-else type="warning" size="small" @click="userEnable(scope.row.userId,true)">启用</el-button>
      </template>
    </table-model>

    <!-- 弹窗start -->
    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form ref="userData" :model="userData" :rules="rules" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="User ID">
          <span>{{ userData.userId }}</span>
        </el-form-item>
        <el-form-item label="姓名">
          <span>{{ userData.userName }}</span>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userData.email" />
        </el-form-item>
        <el-form-item label="会员版本" prop="versionId">
          <el-select v-model="userData.versionId" placeholder="请选择会员版本" prop="platform" @change="versionChange">
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="showDate" label="到期时间" prop="expireTime">
          <el-date-picker v-model="userData.expireTime" value-format="timestamp" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="name">
          <el-input v-model="userData.desc" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateInfo('userData')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 弹窗end -->
  </div>
</template>

<script>
import { getUserList, enable, get, update, check } from '@/api/user'
import { getList as getProductList } from '@/api/product'
import tableModel from '@/components/Table'
import { formatDate } from '@/utils'

export default {
  components: { tableModel },
  data() {
    // 邮箱验证
    const validateEmail = (rule, value, callback) => {
      const other = this
      const params = {}
      debugger
      params.userId = other.userData.userId
      params.email = value
      check(params).then(response => {
        if (response.data === true) {
          callback()
        } else {
          callback(new Error('邮箱已被占用'))
        }
      }).catch(error => {
        console.log(error)
        callback(new Error('服务器错误！'))
      })
    }
    return {
      queryParams: {
        email: '',
        userId: '',
        channelType: '',
        vipVersion: '',
        expired: '',
        state: '',
        page: 1,
        pageSize: 10
      },
      userData: {
        userId: null,
        userName: null,
        email: null,
        versionId: null,
        expireTime: null,
        desc: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱' },
          { trigger: 'blur', validator: validateEmail }
        ],
        versionId: [
          { required: true, message: '请选择会员版本' }
        ],
        expireTime: [
          { required: true, message: '请选到期时间' }
        ]
      },
      dialogFormVisible: false,
      productList: null,
      showDate: false,
      channelTypes: [
        {
          text: '无',
          value: 0
        },
        {
          text: 'googleads',
          value: 1
        },
        {
          text: 'producthunt',
          value: 2
        },
        {
          text: 'baidu',
          value: 3
        }
      ],
      expireds: [
        {
          text: '已过期',
          value: '0'
        },
        {
          text: '未过期',
          value: '1'
        }
      ],
      userState: [
        {
          text: '正常',
          value: true
        },
        {
          text: '封禁',
          value: false
        }
      ],
      columns: [
        {
          text: 'User ID',
          value: 'userId'
        },
        {
          text: '姓名',
          value: 'userName'
        },
        {
          text: '电子邮箱',
          value: 'email'
        },
        {
          text: '注册渠道',
          value: 'channel'
        },
        {
          text: '注册时间',
          value: 'createTime'
        },
        {
          text: '最后登录时间',
          value: 'lastLoginTime'
        },
        {
          text: '会员版本',
          value: 'roleId'
        },
        {
          text: '过期时间',
          value: 'expired'
        },
        {
          text: '备注',
          value: 'updateDesc'
        }
      ]
    }
  },
  created() {
    console.log('one')
    this.fetchInitData()
  },
  methods: {
    // 分页方法
    getPage(params) {
      console.log('three')
      return new Promise((resolve, reject) => {
        getUserList(params).then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    fetchInitData() {
      getProductList().then(response => {
        this.productList = response.data
        console.log(this.productList)
        console.log(response.data)
        console.log('tow')
        this.fetchData()
      })
    }, // 调用table-model的分页方法
    fetchData() {
      this.$refs.tableModel.getPage(this.queryParams)
    },
    search() {
      this.queryParams.page = 1
      this.fetchData()
    },
    // 操作表格数据
    handelData(data) {
      const other = this
      data.forEach(d => {
        console.log(d)
        other.channelTypes.forEach(c => {
          console.log(c)
          if (c.value === Number(d.channel)) {
            d.channel = c.text
          }
        })
        other.productList.forEach(p => {
          console.log(p)
          if (p.id === d.roleId) {
            d.roleId = p.name
          }
        })
        d.createTime = d.createTime === null ? '' : formatDate(d.createTime, 'yyyy-MM-dd hh:mm:ss')
        d.lastLoginTime = d.lastLoginTime === null ? '' : formatDate(d.lastLoginTime, 'yyyy-MM-dd hh:mm:ss')
      })
      return data
    },
    // 启用禁用
    userEnable(userId, state) {
      const other = this
      const params = {}
      params.userId = userId
      params.state = state
      let msg = '您确定要禁用该账号么'
      if (state) {
        // eslint-disable-next-line no-const-assign
        msg = '您确定要启用该账号么'
      }
      this.$confirm(msg, { type: 'warning', confirmButtonText: '确认', cancelButtonText: '取消' })
        .then(_ => {
          enable(params).then(() => {
            other.$message.success('操作成功')
            debugger
            other.$refs.tableModel.refreshPage()
          })
        })
        .catch(_ => {
          other.$message.error('操作失败')
        })
    },
    // 根据用户ID进行查询
    getUserInfo(user) {
      debugger
      const other = this
      get(user.userId).then(response => {
        other.userData = response.data
        this.versionChange(other.userData.versionId)
        other.dialogFormVisible = true
      })
    },
    // 更新用户
    updateInfo(formName) {
      const other = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          other.dialogFormVisible = false
          update(other.userData).then(() => {
            other.userData = {
              userId: null,
              userName: null,
              email: null,
              versionId: null,
              expireTime: null,
              desc: ''
            }
            other.dialogFormVisible = false
            other.$message.success('操作成功')
            other.$refs.tableModel.refreshPage()
          })
        }
      })
    },
    versionChange(event) {
      if (event === '1') {
        this.showDate = false
      } else {
        this.showDate = true
      }
    }
  }
}
</script>
